#include "Acceptor.hpp"
#include "Socket.hpp"
#include <asm-generic/socket.h>
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <netinet/in.h>
using std::cout;
using std::endl;



namespace wd{


Acceptor::Acceptor(unsigned short port, string ip)
:_addr(port,ip)
,_sock()
{
    ready();
}

int Acceptor::accept(){
    int clientfd = ::accept(_sock.fd(),NULL,NULL);
    if(clientfd < 0){
        perror("accept");
        exit(EXIT_FAILURE);
    }
    return clientfd;
}
    
int Acceptor::listenfd(){
    return _sock.fd();
}


void Acceptor::ready() //在构造函数中调用
{
    setReuseAddr(true);
    setReusePort(true);
   
    bind();
    listen();

}

void Acceptor::setReuseAddr(bool flag){
    if(flag){
        int on = 1;
        setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    }
}

void Acceptor::setReusePort(bool flag){
    if(flag){
        int on = 1;
        setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEPORT,&on,sizeof(on));
    }
}
    
void Acceptor::bind(){
    int ret = ::bind(_sock.fd(),(struct sockaddr*)_addr.getInetAddrptr(),sizeof(_addr));
    if(ret < 0){
        perror("bind");
        exit(EXIT_FAILURE);
    }
}
    
void Acceptor::listen(){
    int ret = ::listen(_sock.fd(),100);
    if(ret < 0){
        perror("listen");
    }
}



}
